package com.tanhua.sso.service;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanhua.sso.mapper.UserMapper;
import com.tanhua.sso.pojo.User;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.joda.time.DateTime;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;


import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class UserService {
    //定义static 静态只创建一次 ,final保证只对应一个日志,读取速度快
    private static final Logger LOGGER = LoggerFactory.getLogger(UserService.class);

    @Autowired
    private UserMapper userMapper;

    @Autowired
    //Redis Template 是redis中的api之一,直接@Autowired注入拿点调用即可
    private RedisTemplate<String, String> redisTemplate;

    @Value("${jwt.secret}")
    private String secret;

    //mapper做映射
    private static final ObjectMapper MAPPER = new ObjectMapper();

    @Autowired
    //RocketMQTemplate是RocketMQ集成到Spring cloud之后提供的个方便发送消息的模板类
    //使用的是org.springframework.messaging中的message
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private HuanxinService huanxinService;


    public String login(String mobile, String code) {
        //mobile可移动电话--这里是账号
        //check code 校验码
        String redisKey = "CHECK_CODE_" + mobile;
        //Redid Template中的opsForValue中的get方法是获取对应的key值
        String codeValue = this.redisTemplate.opsForValue().get(redisKey);
        if (StringUtils.isEmpty(codeValue)) {
            //验证码失效
            return null;
        }
        if (!StringUtils.equals(codeValue, code)) {
            //验证码输入有误
            return null;
        }
        //验证码在校验完成后，需要废弃
        this.redisTemplate.delete(redisKey);

        boolean isNew = false;
        //默认是已经注册
        //校验该手机号是否已经注册,如果没有注册,需要重新注册
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile", mobile);
        User user = this.userMapper.selectOne(queryWrapper);
        if (null == user) {
            //该手机号没有注册
            user = new User();
            user.setMobile(mobile);
            //默认密码
            user.setPassword(DigestUtils.md5Hex("123456"));
            this.userMapper.insert(user);

            isNew = true;

            //注册用户到环信平台
            this.huanxinService.register(user.getId());
        }

        //map做映射
        Map<String, Object> claims = new HashMap<String, Object>();
        claims.put("mobile", mobile);
        claims.put("id", user.getId());
        //生成token,并且使用jwt进行加密后存入redis  企业级使用二次加密
        String token = Jwts.builder()
                .setClaims(claims)//设置响应数据体 claims要求,请求
                //使用HS256加密
                .signWith(SignatureAlgorithm.HS256, secret)//设置加密方法和加密盐
                //设置token超时时间
                .setExpiration(new DateTime().plusHours(25).toDate())
                .compact();//坚持,协定

        try {
            //将token储存到redis中
            String redisTokenKey = "TOKEN" + token;
            String redisTokenValue = MAPPER.writeValueAsString(user);
            this.redisTemplate.opsForValue().set(redisTokenKey, redisTokenValue);
        } catch (Exception e) {
            LOGGER.error("储存token错误");
            return null;
        }

        try {
            //发送消息
            Map<String, Object> msg = new HashMap<>();
            msg.put("id", user.getId());
            msg.put("mobile", mobile);
            msg.put("date", new Date());
            this.rocketMQTemplate.convertAndSend("tanhua-sso-login", msg);
        } catch (Exception e) {
            LOGGER.error("发送信息出现错误", e);
        }
        return isNew + "|" + token;
    }

    public User queryUSerByToken(String token) {
        //解析token
        try {
            Map<String, Object> body = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
            User user = new User();
            user.setId(Long.valueOf(body.get("id").toString()));
            //需要返回user对象中的moblie,需要查询数据库获取到mobile数据
            //如果每次都查询数据库,必然会导致星能问题,需要对用户的手机号进行缓存到redis
            //数据缓存时,需要设置过期时间,过期时间要与token的时间一致
            //如果用户修改了手机号,需要同步修改redis中的数据
            String redisKey = "TANHUA_USER_MOBILE_" + user.getId();
            if (this.redisTemplate.hasKey(redisKey)) {
                String mobile = this.redisTemplate.opsForValue().get(redisKey);
                user.setMobile(mobile);
            } else {
                //查询数据库
                User use = this.userMapper.selectById(user.getId());
                user.setMobile(use.getMobile());
                //将手机号写入到redis中
                //在jwt中的过期时间单位为:秒
                Long timeOut = Long.valueOf(body.get("exp").toString()) * 1000 - System.currentTimeMillis();
                this.redisTemplate.opsForValue().set(redisKey, use.getMobile(), timeOut, TimeUnit.MILLISECONDS);
                //this.redisTemplate.opsForValue().set(redisKey, use.getMobile());
            }
            return user;
        }  catch (ExpiredJwtException e) {
            log.info("token已经过期！ token = " + token);
        } catch (Exception e) {

            log.error("token不合法！ token = "+ token, e);
        }
        return null;
    }

    public Boolean updateNewMobile(Long id, String newPhone) {
        //校验新手机是否注册
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile",newPhone);
        User oldUser = this.userMapper.selectOne(queryWrapper);
        if (null != oldUser){
            //如果不为空,表名该手机号已经注册了
            return false;
        }
        User user = new User();
        user.setId(id);
        user.setMobile(newPhone);
        return this.userMapper.updateById(user)>0;
    }
}
